const net = require("net");
const DHTTable = require("./DHTTable");
const SearchPacket = require("./SearchPacket");
const Singleton = require("./Singleton");
const { getOrigin, getLocalPeerSocketAddress} = require("./State");

function time(time) {
    return new Promise(function (resolve) {
        setTimeout(() => {
            resolve();
        }, time);
    })
}

function queryPeer(image_type, image_file_name, sender_ip, sender_port) {
    return new Promise(async (resolve, reject) => {
        let table = DHTTable.getTable().table;
        if (table.length > 0) {
            let mostClosedPeer = table.reduce((prev, next) => {
                if (sender_ip) {
                    if (next.node.peerIP === sender_ip && next.node.peerPort === sender_port) {
                        return prev;
                    }
                }
                if (next.prefix > prev.prefix) {
                    return next;
                }
                return prev;
            }, table[0]);
            let mostClosedPeerIp = mostClosedPeer.node.peerIP;
            let mostClosedPeerPort = mostClosedPeer.node.peerPort;
            if (mostClosedPeerIp === sender_ip && mostClosedPeerPort === sender_port) {
                throw new Error("Infinite loop............................");
            }
            let local_address = getLocalPeerSocketAddress();
            let client = net.createConnection({
                host: mostClosedPeerIp,
                port: mostClosedPeerPort,
                //localAddress: local_address.ip,
                localPort: local_address.port
            });
            let origin = getOrigin();
            client.on('connect', function () {
                console.log(`\nSending kadPTP request message to ${mostClosedPeerIp}:${mostClosedPeerPort}`);
                let p = SearchPacket.build(7,
                    3,
                    Singleton.getPeerName(),
                    origin.ip,
                    origin.port,
                    image_type,
                    image_file_name
                );
                client.write(p);
                client.end();
            });
            client.on('data', function (data) {
                let chunks = data;
                chunks = null;
            })
            client.on('close', function () {
                resolve();
            });
        }
    })

}
module.exports = {
    queryPeer
}